package com.example.qsindusty.jmm_spline.recombinationfragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.qsindusty.jmm_spline.Config.Config;
import com.example.qsindusty.jmm_spline.OrdeFragment.OrderData;
import com.example.qsindusty.jmm_spline.R;
import com.example.qsindusty.jmm_spline.ReleaseOrder.ReleaseOrderActivity;
import com.example.qsindusty.jmm_spline.childactivity.ChildOrderActivity;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yixin.ystartlibrary.base.BaseFragment;
import com.yixin.ystartlibrary.base.BaseRecyclerAdapter;
import com.yixin.ystartlibrary.utils.DensityUtil;
import com.yixin.ystartlibrary.utils.GeneralPreferencesUtils;
import com.yixin.ystartlibrary.utils.LoadingDialogUtils;
import com.yixin.ystartlibrary.utils.LogUtils;
import com.yixin.ystartlibrary.utils.ToastUtils;
import com.yixin.ystartlibrary.widget.DiverItemDecoration;
import com.yixin.ystartlibrary.widget.EmptyRecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


public class RecombibationFragment extends BaseFragment implements  RecombinationContract.View{
    public static boolean isFresh = false;
    @BindView(R.id.materialHeader)
    MaterialHeader materialHeader;
    @BindView(R.id.recyclerview)
    EmptyRecyclerView recyclerview;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.empty_text)
    TextView emptyText;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    String row = Config.row;//默认为10条
    String page = Config.page; //
    String stutus ="0";
    String status = Config.status_order_UNDISTRIBUTED;//默认为2未接货  未分配司机，已分配司机，未接货 运输中 已完成0-4
    OrderAdapter orderAdapter;
    RecombinationPresenter mPresenter ;

    public RecombibationFragment() {
        // Required empty public constructor
    }


    public static RecombibationFragment newInstance() {
        RecombibationFragment fragment = new RecombibationFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected int getContextView() {
        return 0;
    }
    @Override
    public void onResume() {
        super.onResume();
        if (isFresh) {
            page = "1";
          getRecombinationOrder();
            isFresh = false;
        }
    }


    @Override
    protected void init() {
        bindPresenter();
        initview();
        initrefresh();
        getRecombinationOrder();
    }

    @Override
    protected void initBundleData() {

    }


    private void initrefresh() {
        refreshLayout.setEnableScrollContentWhenLoaded(false);
        refreshLayout.setEnableAutoLoadmore(false);
        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getRecombinationOrder();
                //   mPresenter.getOrder(GeneralPreferencesUtils.getSharedPreference(getActivity(), "token", null), status, row, page);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = "1";
                LogUtils.e("initrefreshpage==" + page);
                getRecombinationOrder();
                //    mPresenter.getOrder(GeneralPreferencesUtils.getSharedPreference(getActivity(), "token", null), status, row, page);

            }
        });
    }



    private void initview() {
        orderAdapter = new OrderAdapter();
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        DiverItemDecoration itemDecoration = new DiverItemDecoration(DiverItemDecoration.VERTICAL);
        itemDecoration.setSize(DensityUtil.dip2px(getActivity(), 0.5f));
        itemDecoration.setColor(ContextCompat.getColor(getActivity(), R.color.default_layout_color));
        recyclerview.addItemDecoration(itemDecoration);
        //解决ScrollView嵌套RecyclerView滑动卡帧
        recyclerview.setNestedScrollingEnabled(false);
        //色通知
        emptyText.setText("点击重新加载");
        recyclerview.setEmptyView(LayoutInflater.from(getActivity()).inflate(R.layout.item_emptyview, null));
        recyclerview.setAdapter(orderAdapter);
    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        unbindPresenter();
    }

    AlertDialog alertDialog;

    @Override
    public void showLoading() {
        alertDialog = LoadingDialogUtils.create(getActivity(), "");
        alertDialog.show();

    }

    @Override
    public void closeLoading() {
        if (alertDialog != null && alertDialog.isShowing())
            alertDialog.dismiss();
    }

    /**
     * 绑定presenter
     */
    @Override
    public void bindPresenter() {
        if (mPresenter == null) {
            mPresenter = new RecombinationPresenter();
        }
        mPresenter.bindView(this);
    }

    /**
     * 解除绑定presenter
     */
    @Override
    public void unbindPresenter() {
        mPresenter.unbindView();
    }

    @Override
    public void getSuccessful(OrderData orderData) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        if (page.equals("1")) {
            LogUtils.i("page==1");
            orderAdapter.clearInfoList();
            orderAdapter.addInfoList(orderData.getData());
        } else {
            orderAdapter.addInfoList(orderData.getData());
        }

        orderAdapter.notifyDataSetChanged();
        int p = Integer.parseInt(page);
        page = String.valueOf(p + 1);
    }

    @Override
    public void getFraier(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        ToastUtils.showLongToast(getActivity(), msg);


    }

    @Override
    public void getNomore(String msg) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        ToastUtils.showLongToast(getActivity(), msg);

    }

    @Override
    public void getRecombinationOrder() {
        String token = GeneralPreferencesUtils.getSharedPreference(getActivity(),Config.token,null);
        mPresenter.getKeyOrder(token,row,page);
    }


    public class OrderAdapter extends BaseRecyclerAdapter<OrderData.DataBean, OrderAdapter.ViewHolder> {
        @Override
        protected void onBindViewHolder(final int position, OrderAdapter.ViewHolder holder) {
            OrderData.DataBean dataBean = getItem(position);
            holder.setvauels(dataBean);
            holder.driverBottom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ReleaseOrderActivity.class);
                intent.putExtra(Config.data,getItem(position));
                startActivity(intent);


                }
            });
        }

        @Override
        protected       OrderAdapter.ViewHolder getViewHolder(ViewGroup parent, int viewType) {
            return new OrderAdapter.ViewHolder(inflate(R.layout.item_order, parent));

        }

        @Override
        protected void onBindItemClickListener(View v, int position) {
            super.onBindItemClickListener(v, position);

            Intent intent = new Intent(getActivity(), ChildOrderActivity.class);
            intent.putExtra(Config.data,getItem(position));
            startActivity(intent);


        }

        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.company)
            TextView company;
            @BindView(R.id.driver_bottom)
            TextView driverBottom;
            @BindView(R.id.order_status)
            TextView orderStatus;
            @BindView(R.id.ordernum)
            TextView ordernum;
            @BindView(R.id.startaddress)
            TextView startaddress;
            @BindView(R.id.endaddress)
            TextView endaddress;
            @BindView(R.id.goodstime)
            TextView goodstime;
            @BindView(R.id.fahuotimelin)
            LinearLayout fahuotimelin;
            @BindView(R.id.requiretime)
            TextView requiretime;
            @BindView(R.id.goods)
            TextView goods;
            @BindView(R.id.jiehuotime)
            TextView jiehuotime;
            @BindView(R.id.jiehuolin)
            LinearLayout jiehuolin;
            @BindView(R.id.ordertime)
            TextView ordertime;
            @BindView(R.id.ordertimelin)
            LinearLayout ordertimelin;
            @BindView(R.id.drviername)
            TextView drviername;
            @BindView(R.id.drivierlin)
            LinearLayout drivierlin;
            @BindView(R.id.carnum)
            TextView carnum;
            @BindView(R.id.carlin)
            LinearLayout carlin;

            ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            void setvauels(OrderData.DataBean dataBean) {
                if (!TextUtils.isEmpty(dataBean.getQYMC()))
                    company.setText(dataBean.getQYMC());

                    driverBottom.setText("创建子订单");
                    driverBottom.setBackgroundResource(R.color.theme_blue);
                    driverBottom.setTextColor(getResources().getColor(R.color.white));
                if (!TextUtils.isEmpty(dataBean.getDH()))
                    ordernum.setText(dataBean.getDH());
                if (!TextUtils.isEmpty(dataBean.getFJRDZ()))
                    startaddress.setText(dataBean.getFJRDZ());
                if (!TextUtils.isEmpty(dataBean.getSJRDZ()))
                    endaddress.setText(dataBean.getSJRDZ());
                if (!TextUtils.isEmpty(dataBean.getFHSJ()))
                    requiretime.setText(dataBean.getFHSJ());
                if (!dataBean.getGOODSLIST().isEmpty()) {
                    StringBuilder goodsName = new StringBuilder();
                    for (OrderData.DataBean.GOODSLISTBean goodslistBean : dataBean.getGOODSLIST()) {
                        goodsName = goodsName.append(goodslistBean.getMC()).append("|").append(goodslistBean.getSL()).append(goodslistBean.getDW()).append("  ");
                    }
                    goods.setText(goodsName);
                }
                drivierlin.setVisibility(View.GONE);
                carlin.setVisibility(View.GONE);
                ordertimelin.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(dataBean.getCJSJ()))
                    ordertime.setText(dataBean.getCJSJ());
             /*   if (!TextUtils.isEmpty(dataBean.getSJXM()))
                    drviername.setText(dataBean.getSJXM());
                else
                    drviername.setText("选择司机");
                if (!TextUtils.isEmpty(dataBean.getCPH()))
                    carnum.setText(dataBean.getCPH());
                else
                    carnum.setText("选择车辆");*/

            }
        }
    }


}
